﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleTest
{
    class ActiveObject2 : IDisposable
    {
        private bool _disposed;
        private Task _lastTask;

        public void Dispose()
        {
//            Console.WriteLine("Dispose() started");

            if (_disposed)
                return;

            if (_lastTask != null)
                _lastTask.Wait();

            _disposed = true;
//            Console.WriteLine("Dispose() finished");
        }

        private void CheckIfDisposed()
        {
            if (_disposed)
                throw new ObjectDisposedException(GetType().FullName);
        }

        public void InvokeAsync(Action action)
        {
            CheckIfDisposed();

            _lastTask = _lastTask == null ? Task.Factory.StartNew(action) : _lastTask.ContinueWith(t => action);
        }
    }
}
